<template>
  <div>
    <h1>登陆</h1>
    <p>
      <input type="text" placeholder="用户名" v-model="username" />
    </p>
    <p>
      <input type="password" placeholder="密码" v-model="password" />
    </p>
    <p>
      <router-link to="/register">注册</router-link>
    </p>
    <p>
      <button @click="submitLogin">登陆</button>
    </p>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
import { useLogin, useStorage } from './hooks/user';
import errorHandler from '../config/errorHandler';

const { username, password, checkUserInfo, submitUserInfo } = useLogin();
const { setUserStorage } = useStorage();
const router = useRouter();

const submitLogin = async () => {
  //当用户名长度小于6位时
  if (!checkUserInfo(username, 6)) {
    alert('用户名长度不小于6位');
    return;
  }
  //当密码长度小于6位时
  if (!checkUserInfo(password, 6)) {
    alert('密码长度不小于6位');
    return;
  }
  try {
    const { err_code, data } = await submitUserInfo();
    //err_code !== 0 时 说明失败
    if (err_code) {
      alert(errorHandler[err_code]);
      return;
    }
    //登陆成功时
    //保存token和level到localStorage
    setUserStorage(data.access_token, data.level);
    //跳转至首页
    router.push('/');
  } catch (e) {
    alert('登陆失败');
  }
};
</script>

